/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.controller.account;

import java.math.BigDecimal;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.waleychain.exchange.consumer.controller.BaseController;
import cn.waleychain.exchange.core.constant.DDIC;
import cn.waleychain.exchange.core.entity.PageInfo;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.result.DefaultResult;
import cn.waleychain.exchange.core.result.IBaseResult;
import cn.waleychain.exchange.core.result.RetResultCode;
import cn.waleychain.exchange.core.utils.SequenceUtils;
import cn.waleychain.exchange.core.vaildate.VaildateHelper;
import cn.waleychain.exchange.feign.AccountServiceFeign;
import cn.waleychain.exchange.feign.CommonServiceFeign;
import cn.waleychain.exchange.feign.UserServiceFeign;
import cn.waleychain.exchange.model.AccountRecharge;
import cn.waleychain.exchange.model.AccountWithdraw;
import cn.waleychain.exchange.model.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(description = "用户资金账户相关接口")
@RestController
@RequestMapping("api/v1/account")
public class AccountController extends BaseController {
	
	private static final Logger mLog = LoggerFactory.getLogger(AccountController.class);
	
	@Autowired
	private AccountServiceFeign accountFeign;
	
	@Autowired
	private UserServiceFeign userFeign;
	
	@Autowired
	private CommonServiceFeign commonFeign;
	
	@RequestMapping(value = "/fetchWithdrowPageList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取CNY提现列表", notes = "获取CNY提现列表，URL: http://{ip}:{port}/{projectName}/api/v1/account/fetchWithdrowPageList", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchAccountWithdrowPageList (
			@ApiParam(value = "用户名", required = false) @RequestParam(required = false) String userName,
			@ApiParam(value = "真实姓名", required = false) @RequestParam(required = false) String realName,
			@ApiParam(value = "搜索开始时间", required = false) @RequestParam(required = false) Date beginDate,
			@ApiParam(value = "搜索结束时间", required = false) @RequestParam(required = false) Date endDate,
			@ApiParam(value = "状态（20 待审核 21 拒绝 22 完成）", required = false) @RequestParam(required = false) Integer status,
			@ApiParam(value = "每次查询多少条数据", required = true) @RequestParam(required = true, defaultValue = "-1") Integer showCount, 
			@ApiParam(value = "当前查询页", required = true) @RequestParam(required = true, defaultValue = "1") Integer currentPage, 
			@RequestHeader String Authorization) throws Exception {

		try {

			PageInfo<AccountWithdraw> page = accountFeign.fetchAccountWithdrowPageList(userName, realName, beginDate, endDate, status, showCount, currentPage);
			
			return DefaultResult.buildSuccessResult(page);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取CNY提现列表");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/fetchRechargePageList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取CNY充值列表", notes = "获取CNY充值列表，URL: http://{ip}:{port}/{projectName}/api/v1/account/fetchRechargePageList", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult fetchAccountRechargePageList (
			@ApiParam(value = "用户名", required = false) @RequestParam(required = false) String userName,
			@ApiParam(value = "真实姓名", required = false) @RequestParam(required = false) String realName,
			@ApiParam(value = "搜索开始时间", required = false) @RequestParam(required = false) Date beginDate,
			@ApiParam(value = "搜索结束时间", required = false) @RequestParam(required = false) Date endDate,
			@ApiParam(value = "状态（20 待审核 21 拒绝 22 完成）", required = false) @RequestParam(required = false) Integer status,
			@ApiParam(value = "充值序列码", required = false) @RequestParam(required = false) String tradeNo,
			@ApiParam(value = "每次查询多少条数据", required = true) @RequestParam(required = true, defaultValue = "-1") Integer showCount, 
			@ApiParam(value = "当前查询页", required = true) @RequestParam(required = true, defaultValue = "1") Integer currentPage, 
			@RequestHeader String Authorization) throws Exception {

		try {

			PageInfo<AccountRecharge> page = accountFeign.fetchAccountRechargePageList(userName, realName, beginDate, endDate, status, tradeNo, showCount, currentPage);
			
			return DefaultResult.buildSuccessResult(page);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取CNY充值列表");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/withdrawReview", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户提现审核", notes = "用户提现审核，URL: http://{ip}:{port}/{projectName}/api/v1/account/withdrawReview", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult setAccountWithdrawStatus (
			@ApiParam(value = "提现标识ID", required = true) @RequestParam Long idNo,
			@ApiParam(value = "状态（30 待审核 31 拒绝 32 完成）") @RequestParam Integer status,
			@ApiParam(value = "备注说明", required = false) @RequestParam(required = false) String remark,
			@RequestHeader String Authorization) throws Exception {

		try {

			boolean result = accountFeign.setAccountWithdrawStatus(idNo, status, remark);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户提现审核");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/rechargeReview", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户充值审核", notes = "用户充值审核，URL: http://{ip}:{port}/{projectName}/api/v1/account/rechargeReview", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult setAccountRechargeStatus (
			@ApiParam(value = "提现标识ID", required = true) @RequestParam Long idNo,
			@ApiParam(value = "状态（40 待审核 41 到账成功 42 人工到账 43 处理中）") @RequestParam Integer status,
			@ApiParam(value = "备注说明", required = false) @RequestParam(required = false) String remark,
			@RequestHeader String Authorization) throws Exception {

		try {

			boolean result = accountFeign.setAccountRechargeStatus(idNo, status, remark);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户充值审核");
		}

		return DefaultResult.buildFailedResult();
	}

	@RequestMapping(value = "/userWithdraw", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户CNY提现", notes = "用户CNY提现，URL: http://{ip}:{port}/{projectName}/api/v1/account/userWithdraw", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult userWithdraw(
			@ApiParam(value = "用户标识ID") @RequestParam Long userId,
			@ApiParam(value = "提现金额") @RequestParam BigDecimal amount,
			@ApiParam(value = "到账银行卡") @RequestParam Long userBankId,
			@ApiParam(value = "动态验证码", required = true) @RequestParam String mobileCode,
			@ApiParam(value = "交易密码", required = true) @RequestParam String payPassword,
			@RequestHeader String Authorization) throws Exception {

		try {

			// 获取用户账户
			UserInfo user = userFeign.fetchUserInfo(userId);
			VaildateHelper.vaildateBooleanResult(user == null, RetResultCode.E20019, userId);
			
			commonFeign.vaildateSmsCode(user.getMobile(), mobileCode); // 验证验证码
			
			// 检查是否设置支付密码
			VaildateHelper.vaildateBooleanResult(DDIC.Boolean.BOOL_TRUE_1.id != user.getIsSetPayPassword(), RetResultCode.E20011);
			
			AccountWithdraw accountWithdraw = new AccountWithdraw();
			accountWithdraw.setIdNo(SequenceUtils.generateDefaultSerialNum());
			accountWithdraw.setAmount(amount);
			accountWithdraw.setUserBankId(userBankId);
			accountWithdraw.setCreateTime(new Date());
			accountWithdraw.setModifiedTime(new Date());
			
			boolean result = accountFeign.addAccountWithdraw(accountWithdraw, userId, payPassword);
			
			return DefaultResult.buildSuccessResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户CNY提现");
		}

		return DefaultResult.buildSuccessResult();
	}
	
	@RequestMapping(value = "/userRecharge", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户CNY充值", notes = "用户CNY充值，URL: http://{ip}:{port}/{projectName}/api/v1/account/userRecharge", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult modifyPassword(
			@ApiParam(value = "用户标识ID") @RequestParam Long userId,
			@ApiParam(value = "充值金额") @RequestParam BigDecimal amount,
			@ApiParam(value = "支付类型（1 银联支付 2 支付宝支付 3 微信支付 4 线下支付") @RequestParam(defaultValue = "4") Integer payType,
			@RequestHeader String Authorization) throws Exception {

		try {

			VaildateHelper.vaildateBooleanResult(amount == null, RetResultCode.E11001, "充值金额有误");
			
			VaildateHelper.vaildateIntParams(payType, "支付类型", DDIC.PayType.BANK.id, DDIC.PayType.ALIPAY.id, DDIC.PayType.WECHAT.id, DDIC.PayType.LINEPAY.id);
			
			AccountRecharge accountRecharge = accountFeign.addAccountRecharge(userId, amount, payType);
			
			if (accountRecharge != null) {
				return DefaultResult.buildSuccessResult(accountRecharge);
			}

		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户CNY充值");
		}

		return DefaultResult.buildSuccessResult();
	}
	
}
